package com.educationx;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.util.PreferenceConnector;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.Toast;

public class MainActivity extends Activity {
	private TabHost tabs;
	private ListView courseslist;
	private ListView mycourseslist;
	private Messenger messenger;
	private EditText edittextsearchkey;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		courseslist = (ListView) findViewById(R.id.listRecommended);
		mycourseslist = (ListView) findViewById(R.id.listMyCourses);
		edittextsearchkey = (EditText) findViewById(R.id.editTextSearchKey);
		messenger = new Messenger(handler);

		refreshLists();

		tabs = (TabHost)findViewById(R.id.tabhost);
		tabs.setup();

		TabHost.TabSpec spec = tabs.newTabSpec("tag1");
		spec.setContent(R.id.tab1);
		spec.setIndicator("Recommended Courses");
		tabs.addTab(spec);

		spec = tabs.newTabSpec("tag2");
		spec.setContent(R.id.tab2);
		spec.setIndicator("My Courses");
		tabs.addTab(spec);

		tabs.setOnTabChangedListener(new OnTabChangeListener() {

			@Override
			public void onTabChanged(String arg0) {
				MainActivity.this.refreshLists();
			}
		});
	}

	public void refreshLists() {
		Intent intent_mycourses_service = new Intent(getApplicationContext(), MyCoursesListService.class);
		intent_mycourses_service.putExtra("messenger", messenger);
		intent_mycourses_service.putExtra("userID", PreferenceConnector.readString(getApplicationContext(), "id", "0"));
		startService(intent_mycourses_service);

		Intent intent_recommendedcourses_service = new Intent(getApplicationContext(), RecommendedCourseService.class);
		intent_recommendedcourses_service.putExtra("messenger", messenger);
		intent_recommendedcourses_service.putExtra("userID", PreferenceConnector.readString(getApplicationContext(), "id", "0"));
		startService(intent_recommendedcourses_service);
	}
	
	public void searchCourses(View view) {
		Intent go_to_search_activity = new Intent(this, SearchActivity.class);
		go_to_search_activity.putExtra("key", edittextsearchkey.getText().toString());
		startActivity(go_to_search_activity);
	}

	@Override
	protected void onResume() {
		refreshLists();
		super.onResume();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event){
		final EditText myInputField = (EditText) findViewById(R.id.editTextSearchKey);
		// this will happen on first key pressed on hard-keyboard only. Once myInputField 
		// gets the focus again, it will automatically receive further key presses.
		if (!myInputField.hasFocus()){ 
			myInputField.requestFocus();
			myInputField.onKeyDown(keyCode, event);
		}
		return super.onKeyDown(keyCode, event);
	}

	private Handler handler = new Handler() {

		public void handleMessage(Message message) {
			if(message.obj == null) {
				Toast.makeText(getApplicationContext(), "Couldn't refresh course lists. Servers are temporarily " +
						" down.", Toast.LENGTH_LONG).show();
			} else {
				String response = message.obj.toString();
				try {
					JSONObject jsonResponse = new JSONObject(response);
					if(message.arg1 == Services.MY_COURSES) {
						JSONArray jsonArray = jsonResponse.getJSONArray("myCoursesList");
						List<Course> courses = parseCourses(jsonArray);
						CourseListArrayAdapter adapter = new CourseListArrayAdapter (MainActivity.this, R.layout.row_main, courses);
						mycourseslist.setAdapter(adapter);
						mycourseslist.setOnItemClickListener(new CourseListOnItemClickListener(MainActivity.this, courses, true));
					} else if(message.arg1 == Services.RECOMMENDED_COURSES) {
						JSONArray jsonArray = jsonResponse.getJSONArray("recommendedCoursesList");
						List<Course> courses = parseCourses(jsonArray);
						CourseListArrayAdapter adapter = new CourseListArrayAdapter (MainActivity.this, R.layout.row_main, courses);
						courseslist.setAdapter(adapter);
						courseslist.setOnItemClickListener(new CourseListOnItemClickListener(MainActivity.this, courses, false));
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}

		private List<Course> parseCourses(JSONArray jsonArray) throws JSONException {
			List<Course> courses = new ArrayList<Course>();

			for(int i = 0; i < jsonArray.length(); i++) {
				String id = jsonArray.getJSONObject(i).getString("courseID");
				String name = jsonArray.getJSONObject(i).getString("courseName");
				Course course = new Course(id, name);
				courses.add(course);
			}
			return courses;
		}
	};
}
